  package com.e2e.haiti.infrastructure.surveyor;

import java.io.File;
import java.io.IOException;

import com.actionbarsherlock.app.SherlockFragment;
import com.e2e.haiti.infrastructure.surveyor.R;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

public class FragmentExteriorPhotos  extends SherlockFragment {
	
    private Utils utilsHelper = null;
    private Cursor structureCursor = null;
    private int structureID;
    private Context mContext =  null;
    private static int CAPTURE_IMAGE = -1;
    private View mView = null;
    
    private double longitude = 0;
    private double latitude = 0;
    
    private static final int CAPTURE_IMAGE_FRONT = 0;
    private static final int CAPTURE_IMAGE_RIGHT = 1;
    private static final int CAPTURE_IMAGE_BACK = 2;
    private static final int CAPTURE_IMAGE_LEFT = 3;
    
    private EditText EditText_Exterior_PhotoFront = null;
	private EditText EditText_Exterior_PhotoRight = null;    
	private EditText EditText_Exterior_PhotoBack = null;
	private EditText EditText_Exterior_PhotoLeft = null;    

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
                
        utilsHelper = new Utils(getActivity().getApplicationContext());              
                 
    } // end of the onCreate method
    
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
    	
    	// Sets the cursor
        setStructureCursor(); 
    	
    	View mView = inflater.inflate(R.layout.exterior_photos_layout, container, false);
   		setupPhotoButtons(mView);
    	manageFormFields(mView);
   		

   		return mView;
    }
    
    private void setStructureCursor(){
        utilsHelper.openDatabase(); 
   	   // Get structure ID
          structureID = getActivity().getIntent().getIntExtra("structureID", -1); //Get structureID otherwise -1      
          structureCursor = utilsHelper.getStructureCursor(structureID); 
          utilsHelper.closeDatabase(); 
      }


    private void setupPhotoButtons(View v){
    	
    	// Front Photo Button =================================================================================
    	ImageButton btnFront = (ImageButton) v.findViewById(R.id.btnExteriorFront);
    	
        if (photoAlreadyTaken(CAPTURE_IMAGE_FRONT)){
	        btnFront.setImageResource(R.drawable.check);
        } 
    	
        btnFront.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
               	takePhoto(CAPTURE_IMAGE_FRONT);
           
            }
        }); // End of Front button click listener   
    	
    	// Right Photo Button =================================================================================
        ImageButton btnRight = (ImageButton) v.findViewById(R.id.btnExteriorRight);
        
        if (photoAlreadyTaken(CAPTURE_IMAGE_RIGHT)){
	        btnRight.setImageResource(R.drawable.check);
        } 
        
        btnRight.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
               	takePhoto(CAPTURE_IMAGE_RIGHT);
                   	
           
            }
        }); // End of Right button click listener   
        
    	//  Back Photo Button =================================================================================
        ImageButton btnBack = (ImageButton) v.findViewById(R.id.btnExteriorBack);
        
        if (photoAlreadyTaken(CAPTURE_IMAGE_BACK)){
	        btnBack.setImageResource(R.drawable.check);
        } 
        
        btnBack.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                   	takePhoto(CAPTURE_IMAGE_BACK);
          
            }
        }); // End of  Back button click listener   
        
    	// Left Photo Button =================================================================================
        ImageButton btnLeft = (ImageButton) v.findViewById(R.id.btnExteriorLeft);
        
        if (photoAlreadyTaken(CAPTURE_IMAGE_LEFT)){
		        btnLeft.setImageResource(R.drawable.check);
        } 

        btnLeft.setOnClickListener(new OnClickListener() {
        	
            public void onClick(View v) {
               	takePhoto(CAPTURE_IMAGE_LEFT);           	
           
            }        
        }); // End of Left button click listener    	  	
    }  
    
    private boolean photoAlreadyTaken(int photoSide){
    	
    	boolean exists = false;
    	String photo_value =  null;
    	
    	switch (photoSide){
    	
    		case CAPTURE_IMAGE_FRONT:
    	        photo_value = structureCursor.getString(structureCursor.getColumnIndex(SqlHelper.COLUMN_STRUCTURE_PHOTO_FRONT));
    			break;
    			
    		case CAPTURE_IMAGE_RIGHT:
    	        photo_value = structureCursor.getString(structureCursor.getColumnIndex(SqlHelper.COLUMN_STRUCTURE_PHOTO_RIGHT));
    			break;
    			
    		case CAPTURE_IMAGE_BACK:
    	        photo_value = structureCursor.getString(structureCursor.getColumnIndex(SqlHelper.COLUMN_STRUCTURE_PHOTO_BACK));
    			break;
    			
    		case CAPTURE_IMAGE_LEFT:
    	        photo_value = structureCursor.getString(structureCursor.getColumnIndex(SqlHelper.COLUMN_STRUCTURE_PHOTO_LEFT));
    			break;
    			
            default:
//            	Log.d(LAYOUT_INFLATER_SERVICE, "IMAGE EXISTS ERROR");
            	break;	
    			    	
    	}
    	
    	if (photo_value != null){
    		if (!photo_value.equals("")){
    			exists = true;
    		}    	
    	}

    	return  exists;
    }
    
    private void manageFormFields(View v){

    	// Declares the text input fields
    	EditText_Exterior_PhotoFront = (EditText) v.findViewById(R.id.Exterior_editText_photoFront);
    	EditText_Exterior_PhotoRight = (EditText) v.findViewById(R.id.Exterior_editText_photoRight);    
    	EditText_Exterior_PhotoBack = (EditText) v.findViewById(R.id.Exterior_editText_photoBack);
    	EditText_Exterior_PhotoLeft = (EditText) v.findViewById(R.id.Exterior_editText_photoLeft);    
	    
        // Checks if data already exists for Edit Text
        String photoFrontNote = structureCursor.getString(structureCursor.getColumnIndex(SqlHelper.COLUMN_STRUCTURE_NOTE_FRONT));
		String photoRightNote = structureCursor.getString(structureCursor.getColumnIndex(SqlHelper.COLUMN_STRUCTURE_NOTE_RIGHT));
		String photoBackNote = structureCursor.getString(structureCursor.getColumnIndex(SqlHelper.COLUMN_STRUCTURE_NOTE_BACK));
		String photoLeftNote = structureCursor.getString(structureCursor.getColumnIndex(SqlHelper.COLUMN_STRUCTURE_NOTE_LEFT));
		
		// Sets the text of the input fields
		EditText_Exterior_PhotoFront.setText(photoFrontNote);
		EditText_Exterior_PhotoRight.setText(photoRightNote);    
		EditText_Exterior_PhotoBack.setText(photoBackNote);
		EditText_Exterior_PhotoLeft.setText(photoLeftNote);    
    }   
    
    private void takePhoto(int photoSide){
    	
    	// Determines which photo
    	CAPTURE_IMAGE = photoSide;
    	
    	String photoPath = getPhotoPath(photoSide); 
    	        
        File outFile = new File(photoPath); 	
    	Uri iImageOutputUri = Uri.fromFile( outFile );

    	// Start camera intent to capture image and store the file locally
    	// REQ: 3.4.4.R3 met
    	Intent intent = new Intent( MediaStore.ACTION_IMAGE_CAPTURE );
    	intent.putExtra( MediaStore.EXTRA_OUTPUT, iImageOutputUri );

        utilsHelper.closeDatabase();
        
    	startActivityForResult(intent, CAPTURE_IMAGE);  	
    	}
    
    private String getPhotoPath(int photoSide){
    	    	
    	
		File file = Environment.getExternalStorageDirectory();
	    String structureName = structureCursor.getString(structureCursor.getColumnIndex(SqlHelper.COLUMN_STRUCTURE_NAME));	 			
        String photo_directory = file.getAbsolutePath() + "/Haiti_Structure_Photos/" + structureName ;
        
        // Creates new directory if needed
    	File dir = new File(photo_directory);
        if (!dir.isDirectory())
            dir.mkdirs();
        
        String photoSideText = "";
    	
    	switch (photoSide){
    		
    		case CAPTURE_IMAGE_FRONT:
    			photoSideText = "Front";
    			break;
    		case CAPTURE_IMAGE_RIGHT:
    			photoSideText = "RIGHT";
    			break;
    			
    		case CAPTURE_IMAGE_BACK:
    			photoSideText = "Back";
    			break;
    			
    		case CAPTURE_IMAGE_LEFT:
    			photoSideText = "Left";
    			break;
    			
            default:
//            	Log.d(LAYOUT_INFLATER_SERVICE, "Wrong Image");
            	break;		 		    		
    	}
    	
    	String photoPath = photo_directory + File.separator + structureName + "_" + photoSideText + ".jpg";
		
    	return photoPath;  		
    }
    
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) { 
    	
	 	if (resultCode == getActivity().RESULT_OK) {
	 		
	        utilsHelper.openDatabase();
	 		
	 		if (requestCode == CAPTURE_IMAGE_FRONT){
	 	        String photoPath = getPhotoPath(CAPTURE_IMAGE_FRONT);
	 	        File photo = new File(photoPath);
	 	        
	 			if (photo.exists()){
	 		        
	                String[][] databaseUpdates = {
	                        {SqlHelper.COLUMN_STRUCTURE_PHOTO_FRONT, photoPath},
	                        };
	                utilsHelper.dbHelper.updateStructureEntry(databaseUpdates, structureID ); 
	 				
	 				ImageButton btnFront = (ImageButton) getView().findViewById(R.id.btnExteriorFront);
	 		        btnFront.setImageResource(R.drawable.check);
		 			Toast.makeText(getActivity(),"Photo saved",Toast.LENGTH_SHORT).show(); 	 			
		 		}

	 		}
	 		if (requestCode == CAPTURE_IMAGE_RIGHT){
	 	        String photoPath = getPhotoPath(CAPTURE_IMAGE_RIGHT);
	 	        File photo = new File(photoPath);
	 	        	 			 
	 			if (photo.exists()){
	 				
	                String[][] databaseUpdates = {
	                        {SqlHelper.COLUMN_STRUCTURE_PHOTO_RIGHT, photoPath},
	                        };
	                
	                utilsHelper.dbHelper.updateStructureEntry(databaseUpdates, structureID ); 
	 						
	 		        ImageButton btnRight = (ImageButton) getView().findViewById(R.id.btnExteriorRight);
	 		        btnRight.setImageResource(R.drawable.check);
		 			Toast.makeText(getActivity(),"Photo saved",Toast.LENGTH_SHORT).show(); 	 			
		 		}

	 		}
	 		if (requestCode == CAPTURE_IMAGE_BACK){
	 	        String photoPath = getPhotoPath(CAPTURE_IMAGE_BACK);
	 	        File photo = new File(photoPath);
	 	        	 			 
	 			if (photo.exists()){
	 				
	                String[][] databaseUpdates = {
	                        {SqlHelper.COLUMN_STRUCTURE_PHOTO_BACK, photoPath},
	                        };
	                
	                utilsHelper.dbHelper.updateStructureEntry(databaseUpdates, structureID ); 
	 				
	 		        ImageButton btnBack = (ImageButton) getView().findViewById(R.id.btnExteriorBack);
	 		        btnBack.setImageResource(R.drawable.check);
		 			Toast.makeText(getActivity(),"Photo saved",Toast.LENGTH_SHORT).show(); 	 			
		 		}
	 		}
	 		if (requestCode == CAPTURE_IMAGE_LEFT){
	 	        String photoPath = getPhotoPath(CAPTURE_IMAGE_LEFT);
	 	        File photo = new File(photoPath);
	 	        	 			 
	 			if (photo.exists()){
	 				
	                String[][] databaseUpdates = {
	                        {SqlHelper.COLUMN_STRUCTURE_PHOTO_LEFT, photoPath},
	                        };
	                
	                utilsHelper.dbHelper.updateStructureEntry(databaseUpdates, structureID ); 
	 				
	 		        ImageButton btnLeft = (ImageButton) getView().findViewById(R.id.btnExteriorLeft);
	 		        btnLeft.setImageResource(R.drawable.check);	 			 				
		 			Toast.makeText(getActivity(),"Photo saved",Toast.LENGTH_SHORT).show(); 	 			
		 		}
	 		}
	        
	 		utilsHelper.closeDatabase();

	    } // IF  RESULT ==  OK
  	
    } // On Activity Result
    
} 